package com.example.crm.dao;

import com.example.crm.domain.User;
import com.example.crm.utils.JDBCUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UserDAO {
    public int findByName(String username)throws SQLException
    {
        // 1. 获取连接
        Connection conn = JDBCUtils.getConnection();

        // 2. 创建Statment
        String sql = "select * from user where username=?";
        PreparedStatement stmt = conn.prepareStatement(sql);

        stmt.setString(1, username);

        // 3. 执行层语句
        ResultSet rs = stmt.executeQuery();
        User u = null;
        int result = 0;
        if(rs.next())
        {
            result=1;
        }

        // 4. 释放资源
        JDBCUtils.destory(conn, stmt, null);

        return result;
    }



    public User find(String username, String password) throws SQLException
    {
        // 1.
        System.out.println(JDBCUtils.getConnection());
        Connection conn = JDBCUtils.getConnection();
        // 2.
        String sql = "select * from user where username=? and password=?";
        PreparedStatement stmt = conn.prepareStatement(sql);
        stmt.setString(1, username);
        stmt.setString(2, password);
        // 3.
        ResultSet rs = stmt.executeQuery();
        User user = null;
        if(rs.next())
        {
            int id = rs.getInt(1);
          //  user = new User(id,username,password);
          //  User
             user=new User();
            user.setId(id);
            user.setUsername(username);
            user.setPassword(password);

        }

        return user;
    }

    public int insert(User r) throws SQLException {
        String sql="insert into user values(null,?,?)";
        Connection conn= JDBCUtils.getConnection();
        PreparedStatement stmt=conn.prepareStatement(sql);
        stmt.setString(1,r.getUsername());
        stmt.setString(2,r.getPassword());
        int result;
        try{
            result=stmt.executeUpdate();}
        catch (SQLException throwables) {
            throwables.printStackTrace();
            result=-1;
        }
        System.out.println("影响行数"+result);
        JDBCUtils.destory(conn,stmt,null);
        return result;
    }


}
